<template>
    <!-- 车企编辑弹框 -->
    <CommonModal v-model="state.visible" @handleOk="handleOk" @handleCancel="handleCancel" :title="state.modalTitle"
        :width="800" :loading="state.submitting">
        {{ state.showType }} 12 3123
        <a-tabs v-model:activeKey="state.activeTab" class="car-company-tabs" @change="handleTabChange">
            <!-- 基本信息标签页 -->
            <a-tab-pane key="basic" tab="基本信息">
                <a-form class="form_box" ref="formRef" name="custom-validation" :model="formState" :rules="rules"
                    v-bind="layout">

                    <a-form-item has-feedback label="车企名称" name="name" :colon="false">
                        <a-input    
                        :disabled="state.showType == 'view'" v-model:value="formState.name" autocomplete="off" placeholder="请输入车企名称" />
                    </a-form-item>

                    <a-form-item has-feedback label="营业执照照片" name="businessLicense" :colon="false">
                        <!-- {{ formState.businessLicense }} -->
                        <SQuploadFile :maxCount="1" :files="formState.businessLicense"
                        :disabled="state.showType == 'view'"
                            @change="changeBusinessLicense">
                            <!-- :minWidth="700"
                            :minHeight="700" -->
                            <template #tip>
                                注:需提供三证合一/二证合一的营业执照原件扫描件或加盖公司鲜章的复印件,图片尺寸为700*700px以上,支持PNG、JPG和JPEG格式,大小不超过5MB
                            </template>
                        </SQuploadFile>

                    </a-form-item>

                    <a-form-item has-feedback label="身份证信息" name="idCardInfo" :colon="false">
                        <div class="id-card-upload">
                            <div class="id-card-item">
                                <div class="upload-label">人像面</div>
                                <SQuploadFile :maxCount="1" :files="formState.idcardFront"
                                :disabled="state.showType == 'view'"
                                @change="changeIdCardFront">
                                </SQuploadFile>
                            </div>


                            <a-form-item-rest>



                                <div class="id-card-item">
                                    <div class="upload-label">国徽面</div>
                                    <SQuploadFile :maxCount="1" :files="formState.idcardBack"
                                    :disabled="state.showType == 'view'"
                                    @change="changeIdCardBack">
                                    </SQuploadFile>
                                </div>
                            </a-form-item-rest>
                        </div>
                    </a-form-item>

                    <a-form-item has-feedback label="法定代表人姓名" name="legalName" :colon="false">
                        <a-input :disabled="state.showType == 'view'" v-model:value="formState.legalName" autocomplete="off"
                            placeholder="请输入法定代表人姓名" />
                    </a-form-item>

                    <a-form-item has-feedback label="负责人姓名" name="directorName" :colon="false">
                        <a-input :disabled="state.showType == 'view'" v-model:value="formState.directorName" autocomplete="off" placeholder="请输入负责人姓名" />
                    </a-form-item>

                    <a-form-item has-feedback label="负责人电话" name="directorPhone" :colon="false">
                        <a-input :disabled="state.showType == 'view'" v-model:value="formState.directorPhone" autocomplete="off" placeholder="请输入负责人电话" />
                    </a-form-item>

                    <a-form-item has-feedback label="描述" name="description" :colon="false">
                        <a-textarea :disabled="state.showType == 'view'"    v-model:value="formState.description" placeholder="请输入描述信息" :rows="3" />
                    </a-form-item>
                </a-form>
            </a-tab-pane>

            <!-- 运营区域标签页 -->
            <a-tab-pane key="operationArea" tab="运营区域">
                <div class="operation-area-content">
                    <div class="area-selection">
                        <div class="area-title">运营区域围栏:</div>
                        <!-- {{ formState.fenceIdList }} -->
                        <a-select :disabled="state.showType == 'view'" v-model:value="formState.fenceIdList" mode="multiple" style="width: 100%"
                            placeholder="请选择运营区域" :options="areaOptions" @change="handleAreaChange" />
                    </div>

                    <div class="map-section">
                        <div class="map-header">
                            <a-input :disabled="state.showType == 'view'"   placeholder="搜索/选择地址" id='search_station' style="width: 200px;" v-model:value="searchAddress"/>
                           
                        </div>
                        <div id="operation-map" class="map-content"></div>
                    </div>
                </div>
            </a-tab-pane>

            <!-- 运营车辆标签页 -->
            <a-tab-pane key="operationVehicles" tab="运营车辆">
                <div class="vehicleFenceList-content">
                    <div class="vehicleFenceList-header">
                        <h4>车辆列表</h4>

                    </div>
                    <a-table :columns="vehicleColumns" :data-source="formState.vehicleFenceList" :pagination="false"
                        size="small">
                        <template #bodyCell="{ column,record }">
                            <template v-if="column.dataIndex === 'fenceId'">
                                {{ record.fenceId }}
                                <a-select :disabled="state.showType == 'view'" v-model:value="record.fenceId"  style="width: 150px"
                                placeholder="请选择运营区域" :options="vehicleFenceIdOptions"/>
                                
                            </template>
                        </template>
                    </a-table>
                </div>
            </a-tab-pane>
        </a-tabs>
    </CommonModal>
</template>

<script setup>
import { reactive, ref, onMounted, onUnmounted, computed } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { bizManufacturerAdd, bizManufacturerUpdate, bizManufacturerDetail } from "@/service/nmcApi"
import { getFenceArea } from '@/utils/baseData'
const emit = defineEmits(['success'])

const state = reactive({
    visible: false,
    modalTitle: '编辑',
    activeTab: 'basic',
    submitting: false, // 添加提交状态
    showType: 'edit' // 显示类型 add 新增 edit 编辑 view 查看详情
})

const formRef = ref()
const searchAddress = ref('')

// 表单数据
const formState = reactive({
    name: '', // 车企名称
    businessLicense: '', // 营业执照
    idcardFront: '', // 身份证正面
    idcardBack: '', // 身份证反面
    legalName: '', // 法人代表名称
    directorName: '', // 负责人姓名
    directorPhone: '', // 负责人电话
    description: '', // 描述
    // operationAreas: [],  // 运营区域
    // vehicleFenceList: [],
    fenceIdList: [], // 新增：用于存储选中的区域名称
    vehicleFenceList:[] // 运营车辆
})

// 区域选项数据
const areaOptions = ref([

])

// 表单验证规则
const rules = {
    name: [{ required: true, message: '请输入车企名称' }],
    directorName: [{ required: true, message: '请输入负责人姓名' }],
    directorPhone: [
        { required: true, message: '请输入负责人电话' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
    ]
}

// 表单布局
const layout = {
    labelCol: {
        span: 6
    },
    wrapperCol: {
        span: 16,
    },
}

// 车辆表格列配置
const vehicleColumns = [
    {
        title: '车牌号',
        dataIndex: 'plateLicense',
        width: 120
    },
    {
        title: '车架号',
        dataIndex: 'plateVin',
        width: 100
    },
    {
        title: '车辆状态',
        // dataIndex: 'optStatus',
        // width: 100
    },
    {
        title: '运营生效时间',
        dataIndex: 'fprq',
        width: 120
    },
    {
        title: '运营截止时间',
        dataIndex: 'sxrq',
        width: 120
    },
    {
        title: '运营区域',
        dataIndex: 'fenceId',
        width: 120
    }
]

// 地图相关变量
let mapInstance = null, gaoAutoComplete = null
let polygons = []

onMounted(async () => {
    
})

onUnmounted(() => {
    if (mapInstance) {
        mapInstance.destroy()
    }
})

// 初始化地图
const initMap = () => {
    if (mapInstance) return
    
    mapInstance = new AMap.Map('operation-map', {
        mapStyle: 'amap://styles/whitesmoke',
        doubleClickZoom: false,
        zoom: 13,
        center: [114.325512, 30.367111],
        animateEnable: false
    })
    mapInstance.plugin(['AMap.AutoComplete'], () => {
        gaoAutoComplete = new AMap.AutoComplete({
            input: 'search_station',
        })
        gaoAutoComplete.on('select', handleSelectResult)
    })
}
//高德搜索
const handleSelectResult = (e) => {
    // console.log(e.poi, searchMarker)
    if (e.poi.location) {
        const { lng, lat } = e.poi.location;
        // 地图重新定位
        mapInstance.setCenter(e.poi.location);
        mapInstance.setZoom(16);
    }
}
// 文件上传处理
const changeBusinessLicense = (files) => {
    formState.businessLicense = files
    // if (files && files.length > 0) {
    //     message.success('营业执照上传成功')
    // }
}

const changeIdCardFront = (files) => {
    formState.idcardFront = files
    if (files && files.length > 0) {
        message.success('身份证正面上传成功')
    }
}

const changeIdCardBack = (files) => {
    formState.idcardBack = files
    if (files && files.length > 0) {
        message.success('身份证反面上传成功')
    }
}

// 区域选择处理
const handleAreaChange = (selectedValues) => {
    // formState.fenceIdList = selectedValues
    // 更新地图显示
    updateMapDisplay()
    // 更新车辆运营区域
    formState.vehicleFenceList.forEach(item => {
        item.fenceId = selectedValues.find(value => value === item.fenceId) || null
    })
}

// 更新地图显示
const updateMapDisplay = () => {
    // 清除现有的多边形
    polygons.forEach(polygon => {
        if (polygon && mapInstance) {
            mapInstance.remove(polygon)
        }
    })
    polygons = []

    console.log(formState.fenceIdList,'areaOptions',areaOptions.value)
    // 绘制选中的区域
    formState.fenceIdList.forEach((areaName, index) => {
        const areaOption = areaOptions.value.find(option => option.value === areaName)
        if (areaOption && areaOption.bizFenceAreaList) {
            areaOption.bizFenceAreaList.map(item => {
                const polygon = new AMap.Polygon({
                    path: item.pointList.map(point => [point.lo, point.la]),
                    fillColor: '#1890ff',
                    fillOpacity: 0.3,
                    strokeWeight: 2,
                    strokeColor: '#1890ff'
                })

                mapInstance.add(polygon)
                polygons.push(polygon)
            })


        }
    })

    // 调整地图视野以显示所有多边形
    if (polygons.length > 0) {
        mapInstance.setFitView(polygons, false, [60, 60, 60, 60], 16)
    }
}




const vehicleFenceIdOptions = computed(() => {

    // console.log(areaOptions.value,'formState.fenceIdList',formState.fenceIdList)
    return areaOptions.value.filter(option => formState.fenceIdList.includes(option.value))
    // 这里可以打开编辑对话框
    // console.log('编辑车辆:', formState.vehicleFenceList[index])
})



// 显示弹窗
const showModal = async (obj) => {
    state.modalTitle = obj.title || '编辑';
    state.showType = obj.showType || 'edit';
    state.activeTab = 'basic';
    console.log(state.showType,'state.showType',obj)
    if (obj.id) {
        // 编辑模式，加载现有数据
        bizManufacturerDetail({ id: obj.id }).then(res => {
            if (res && res.status === "000_0000_0000") {
                const data = res.data || res.result || {}
                Object.assign(formState, {
                    id: data.id,
                    name: data.name || '',  // 车企名称
                    businessLicense: data.businessLicense || '', // 营业执照
                    idcardFront: data.idcardFront || '', // 身份证正面
                    idcardBack: data.idcardBack || '', // 身份证反面
                    legalName: data.legalName || '', // 法人代表名称
                    directorName: data.directorName || '', // 负责人姓名
                    directorPhone: data.directorPhone || '', // 负责人电话
                    description: data.description || '', // 描述    
                    // operationAreas: data.operationAreas || [], // 运营区域
                    // vehicleFenceList: data.vehicleFenceList || [], // 运营车辆
                    fenceIdList: data.bizFenceDtoList ? data.bizFenceDtoList.map(area => area.id) : [], // 运营区域
                    vehicleFenceList: data.bizVehicleDtoList? data.bizVehicleDtoList.map(item => ({
                        ...item,
                        fenceId: item.fenceId || null
                    })) : [] // 运营车辆
                })
            } else {
                message.error('获取详情失败')
            }
        }).catch(err => {
            console.error('获取详情失败:', err)
            message.error('获取详情失败')
        })
    } else {
        // 新增模式，清空表单
        Object.keys(formState).forEach(key => {
            if (Array.isArray(formState[key])) {
                formState[key] = []
            } else if (key === 'businessLicense' || key === 'idcardFront' || key === 'idcardBack') {
                formState[key] = '' // 文件上传字段设为空字符串
            } else {
                formState[key] = ''
            }
        })
        formState.fenceIdList = [] // 新增：新增模式时清空选中的区域
        // formState.vehicleFenceList = [] // 新增：清空车辆列表
        // formState.operationAreas = [] // 新增：清空运营区域
    }

    state.visible = true;

    // 获取最新的运营区域列表
    const res = await getFenceArea()
    areaOptions.value = res.map(item => ({
        label: item.name,
        value: item.id,
        bizFenceAreaList: item.bizFenceAreaList
    }))
}
const handleTabChange = (key) => {
    if (key === 'operationArea') {
        // 初始化地图
        setTimeout(() => {
            initMap()
            updateMapDisplay()
        }, 100)
    }
}
// 确认
const handleOk = () => {
    if (state.showType === 'view') {
        state.visible = false
        return
    }
    formRef.value.validateFields().then(res => {
        state.submitting = true
        
        // 数据验证
        if (!formState.name.trim()) {
            message.error('请输入车企名称')
            state.submitting = false
            return
        }
        
        if (!formState.directorName.trim()) {
            message.error('请输入负责人姓名')
            state.submitting = false
            return
        }
        
        if (!formState.directorPhone.trim()) {
            message.error('请输入负责人电话')
            state.submitting = false
            return
        }
        
  

        const submitData = {
            ...formState,
            vehicleFenceList:formState.vehicleFenceList.map(item => ({
                vehicleId:item.id,
                fenceId: item.fenceId || null
            }))
     
        }

        // 根据是否有id判断是新增还是编辑
        const apiCall = formState.id ? bizManufacturerUpdate : bizManufacturerAdd
        
        apiCall(submitData).then(res => {
            if (res && res.status === "000_0000_0000") {
                message.success('保存成功')
                state.visible = false
                emit('success', submitData)
            } else {
                message.error(res.message || '保存失败')
            }
        }).catch(err => {
            console.error('保存失败:', err)
            message.error('保存失败')
        }).finally(() => {
            state.submitting = false
        })
    }).catch(err => {
        message.error('表单验证不通过')
    })
}

// 取消
const handleCancel = () => {
    formRef.value.resetFields()
    // 重置表单数据
    Object.keys(formState).forEach(key => {
        if (Array.isArray(formState[key])) {
            formState[key] = []
        } else if (key === 'businessLicense' || key === 'idcardFront' || key === 'idcardBack') {
            formState[key] = ''
        } else {
            formState[key] = ''
        }
    })
    formState.fenceIdList = []; // 新增：清空选中的区域
    // formState.vehicleFenceList = []
    // 销毁地图
    if (mapInstance) {
        mapInstance.destroy();
        mapInstance = null;
    }
    state.visible = false;
}

// 暴露方法给父组件
defineExpose({ showModal })
</script>

<style scoped lang="less">
.car-company-tabs {
    :deep(.ant-tabs-content) {
        height: 500px;
        overflow-y: auto;
    }
}

.form_box {

    input,
    :deep(.JManage-select-selector) {
        height: 32px;
        box-sizing: border-box;
        background: #FFFFFF;
        border-radius: 6px;
        border: 1px solid #E0E0E0;
    }

    :deep(.JManage-form-item-control-input) {
        width: 250px;
    }
}

.upload-tip {
    margin-top: 8px;
    color: #999;
    font-size: 12px;
    line-height: 1.4;
}

.id-card-upload {
    display: flex;
    gap: 20px;

    .id-card-item {
        flex: 1;

        .upload-label {
            margin-bottom: 8px;
            font-size: 14px;
            color: #333;
        }
    }
}

.operation-area-content {
    .area-selection {
        margin-bottom: 20px;

        .area-title {
            margin-bottom: 12px;
            font-weight: 500;
        }
    }

    .map-section {
        border: 1px solid #d9d9d9;
        border-radius: 6px;
        overflow: hidden;
        position: relative;
        .map-header {
            // padding: 12px;
            position: absolute;
            top: 16px;
            left: 16px;
            z-index: 1000;
            // width: 100%;
            // background: #fafafa;
            border-bottom: 1px solid #d9d9d9;
            font-weight: 500;
            color: #333;
        }

        .map-content {
            height: 300px;
        }
    }
}

.vehicleFenceList-content {
    .vehicleFenceList-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        h4 {
            margin: 0;
        }
    }
}
</style>